import { userTB } from '../database/mongodb/index.js'
import { promisePool } from '../database/mysql2/index.js'
import { autoIncreaseId } from './tools.js'
import { configObj } from '../node.config.js'
import jwt from 'jsonwebtoken'
import { secret } from '../config/secret.js'

console.log(`configObj => %O `, configObj)

let isMongoDB = configObj.argv[0] === 'mongodb'

/* 获取一个期限为4小时的token */
function getToken(payload = {}) {
  return jwt.sign(payload, secret, { expiresIn: '4h' })
}

// 插入token
export async function insertToken(username, password) {
  const token =
    'Bearer ' +
    getToken({
      username: username,
      password: password
    })
  const [resultSetHeader] = await promisePool.query(
    `UPDATE user_tb SET token='${token}' WHERE username='${username}' AND password = '${password}'`
  )
  console.log(`resultSetHeader => %O `, resultSetHeader)
}

export async function login(username, password) {
  if (!username || !password) {
    return false
  }

  if (isMongoDB) {
    let findOne = await userTB.findOne({ username, password })
    if (findOne) return findOne

    let findOneByUsername = await userTB.findOne({ username })

    if (findOneByUsername) return { type: '密码错误' }

    return { type: '用户名不存在' }
  } else {
    const [rows] = await promisePool.query(
      `SELECT username,password FROM user_tb WHERE username='${username}' AND password = '${password}'`
    )
    console.log(`rows => %O `, rows)
    if (rows.length) {
      const [rows] = await promisePool.query(
        `SELECT username,password,token FROM user_tb WHERE username='${username}' AND password = '${password}'`
      )
      return rows[0]
    }

    const [rows2] = await promisePool.query(
      `SELECT username,password FROM user_tb WHERE username='${username}'`
    )
    console.log(`rows2 => %O `, rows2)

    if (rows2.length) return { type: '密码错误' }

    return { type: '用户名不存在' }
    // let [resultSetHeader] = await promisePool.execute(
    //   `INSERT INTO user_tb (username,password,date) values("${username}","${password}",DATE)`
    // )
  }
}

export async function register(username, password) {
  // if (user[username] === undefined) {
  //   return false
  // }
  // return user[username] === password

  if (isMongoDB) {
    let findOne = await userTB.findOne({ username })
    if (findOne) return false
    let doc = {
      username,
      password,
      id: await autoIncreaseId(userTB)
    }
    let insertOne = await userTB.insertOne(doc)
    console.log(`insertOne => %O `, insertOne)

    return insertOne
  } else {
    const [rows] = await promisePool.query(
      `SELECT username,password FROM user_tb WHERE username='${username}'`
    )
    console.log(`rows2 => %O `, rows)
    if (rows.length) return false

    let [resultSetHeader] = await promisePool.execute(
      `INSERT INTO user_tb (username,password,date) values("${username}","${password}",DATE)`
    )
    console.log(`resultSetHeader => %O `, resultSetHeader)

    return resultSetHeader
  }
}

export async function registerout(username) {
  if (isMongoDB) {
    let deleteOne = await userTB.deleteOne({ username })
    console.log(`deleteOne => %O `, deleteOne)
    return deleteOne
  } else {
    let [deleteOne] = await promisePool.execute(
      `DELETE FROM user_tb WHERE username='${username}'`
    )
    console.log(`deleteOne => %O `, deleteOne)
    return deleteOne
  }
}

export async function getList() {
  // 获取数据库的字典数据
  const [rows] = await promisePool.query(`SELECT * FROM data_dict`)
  // console.log('rows', rows)
  const buildTree = (data, parentCode = '') => {
    let tree = []
    data.forEach((node) => {
      if (node.parentCode === parentCode) {
        let children = buildTree(data, node.code)
        if (children.length) {
          node.children = children
        }
        tree.push(node)
      }
    })
    return tree
  }
  // 拼接数据
  // console.log('buildTree', JSON.stringify(buildTree(rows)))
  return buildTree(rows)
}
